import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Row, Col } from 'antd';
import moment from 'moment';

import GaugeChart from '../investmentAnalysis/charts/GaugeChart';
import AreaChart from '../investmentAnalysis/charts/AreaChart';
import RadarChart from '../investmentAnalysis/charts/RadarChart';
import utils from '../investmentAnalysis/utils';

const mapStateToProps = state => ({
  currentDataDate: state.retailFeatureList.currentDataDate,
  historyFeatures: state.retailFeatureList.historyFeatures,
  historyAccountDailies: state.retailFeatureList.historyAccountDailies,
});

const mapDispatchToProps = {
  getHistoryFeatures: query => ({
    type: 'retailFeatureList/getHistoryFeatures',
    payload: query || {},
  }),
  getHistoryAccountDailies: query => ({
    type: 'retailFeatureList/getHistoryAccountDailies',
    payload: query || {},
  }),
};

@connect(mapStateToProps, mapDispatchToProps)
export default class FeaturesReport extends Component {
  static propTypes = {
    currentDataDate: PropTypes.object.isRequired,
    features: PropTypes.object,
    featuresMapping: PropTypes.array.isRequired,
    historyFeatures: PropTypes.array,
    getHistoryFeatures: PropTypes.func.isRequired,
  }
  componentDidMount() {
    const { currentDataDate, features: { trader } } = this.props;
    if (trader != null && currentDataDate != null) {
      this.getHistoryFeatures(this.props);
    }
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps !== this.props && nextProps.features !== this.props.features) {
      this.getHistoryFeatures(nextProps);
    }
  }
  getHistoryFeatures = ({ features, currentDataDate, getHistoryFeatures, getHistoryAccountDailies }) => {
    if (features) {
      const { trader } = features;
      const enddate = moment(currentDataDate).format('YYYY-MM-DD');
      const begindate = moment(currentDataDate).add(-30, 'days').format('YYYY-MM-DD');

      const begindate2 = moment(currentDataDate).add(-180, 'days').format('YYYY-MM-DD');
      getHistoryFeatures({ trader, enddate, begindate });
      getHistoryAccountDailies({ trader, enddate, begindate: begindate2 });
    }
  }
  convertData = (historyFeatures) => {
    if (historyFeatures == null || historyFeatures.length === 0) {
      return null;
    }

    const featuresData = {
      all_time_pnl: [],
      trade_count: [],
      sharpe_ratio: [],
    };
    historyFeatures.forEach((item, index) => {
      const dataDate = item.dataDate;
      for (const k in featuresData) {
        featuresData[k].push([dataDate, item[utils.toCamelCase(k)]]);
      }
    });

    return featuresData;
  }
  render() {
    const { features, featuresMapping, historyFeatures, historyAccountDailies } = this.props;
    const featuresData = this.convertData(historyFeatures);
    const nameMap = {};
    featuresMapping && featuresMapping.forEach((item) => {
      nameMap[item.columnName] = item.showName;
    });

    const fieldsConfig1 = {
      profitability: value => value.toFixed(2),
      risk_control: value => value.toFixed(2),
      consistency: value => (value).toFixed(2),
      activity: value => (value).toFixed(2),
    };
    const fields1 = [];
    const data1 = [];

    for (const f in fieldsConfig1) {
      const formatter = fieldsConfig1[f];
      if (formatter) {
        data1.push(formatter(features[utils.toCamelCase(f)]));
      } else {
        data1.push(features[utils.toCamelCase(f)]);
      }
      fields1.push(nameMap[f]);
    }

    const areaData = [];
    const areaDataUnitPrice = [];
    const areaDataClosedPositionsPnl = [];
    historyAccountDailies.forEach((item) => {
      const dataDate = item.dataDate;
      areaData.push([dataDate, item.openPositionsPnl.toFixed(4)]);
      areaDataUnitPrice.push([dataDate, item.unitPrice.toFixed(4)]);
      areaDataClosedPositionsPnl.push([dataDate, item.closedPositionsPnl.toFixed(4)]);
    });

    return (
      <Row gutter={20}>
        <Col span={12}>
          {features.profitability &&
            <div style={{ margin: 15 }}>
              <GaugeChart height="180" name="FDT Score" value={features.fdtScore} />
            </div>}
          {data1 && data1.length > 0 &&
            <div style={{ margin: 10 }}>
              <RadarChart height="250" serieName="综合交易能力" fields={fields1} data={data1} color={'#f96868'} />
            </div>}
        </Col>
        {featuresData &&
          <Col span={12}>
            <AreaChart
              serieNames={['资产净值']}
              serieDatas={[areaDataUnitPrice]}
              colors={['#f96868']}
            />
            <AreaChart
              serieNames={['每日平仓盈亏', '每日浮动盈亏']}
              serieDatas={[areaDataClosedPositionsPnl, areaData]}
              colors={['#A5E6C0', '#FDCC99']}
              isArea={false}
            />
          </Col>
        }
      </Row>
    );
  }
}
